package com._51cto.healthy.minio;

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.Result;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

@Component
public class MinIoService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinIOProperties properties;
    @Autowired
    private RedisTemplate redisTemplate;
    //获取文件后缀
    private String getSuffix(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    @SneakyThrows
    public String uploadImage(MultipartFile file){
        //文件的流对象
        InputStream inputStream = file.getInputStream();
        //上传的文件名
        String fileName = file.getOriginalFilename();
        //生成文件名
        String newName = UUID.randomUUID().toString();
        //后缀名计算
        String suffix = getSuffix(fileName);
        //文件文件名
        System.out.println("文件名："+fileName);
        fileName =newName+suffix;
        //文件文件名
        System.out.println("文件名："+fileName);
        //文件 进行上传
        PutObjectArgs poa = PutObjectArgs.builder()
                .stream(inputStream, file.getSize(), PutObjectArgs.MIN_MULTIPART_SIZE)
                .object(fileName)
                .contentType(file.getContentType())
                .bucket(properties.getBucket())
                .build();
        minioClient.putObject(poa);
        //垃圾处理
        redisTemplate.boundSetOps("UNUSE_IMG").add(fileName);
        //返回文件名 ： 访问域名+桶+文件名S
        String imgUrl = properties.getUrl()+"/"+properties.getBucket()+"/"+fileName;
        return imgUrl;
    }

    public void disposal() {
        //从redis中读取
        Set<String> unUse = redisTemplate.boundSetOps("UNUSE_IMG").members();
        // 封装MINio批量删除Set
        Set<DeleteObject> obs = unUse.stream()
                .map(imgName -> new DeleteObject(imgName))
                .collect(Collectors.toSet());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder()
                .bucket(properties.getBucket())
                .objects(obs)
                .build());
        results.forEach(r-> {
            try {
                DeleteError error = r.get();
                System.out.println("删除错误："+error);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //redis清理
        redisTemplate.delete("UNUSE_IMG");
    }
    //--- 其他代码省略
}
